<?php

namespace App\Http\Controllers\Api;

use App\Models\Pocket;
use App\Models\PocketLog;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class PocketController extends Controller
{
    /**
     * 钱包余额
     */
    public function index(Request $request)
    {
        return Api::success([
            'amount' => price(Auth::user()->pocket->amount / 100),
        ]);
    }

    /**
     * 花费明细
     */
    public function logs(Request $request)
    {
        $query = PocketLog::query()
            ->latest()
            ->where('customer_id', Auth::id());

        $page = $request->input('page', 1) ?: 1;
        $limit = $request->input('limit', 10) ?: 10;

        $skip = ($page - 1) * $limit;

        $logs = $query->skip($skip)->limit($limit)->get();

        return Api::success($logs);

    }

    /**
     * 修改支付密码
     */
    public function password(Request $request)
    {
        $data = $request->all([
            'password',
            'password_confirm',
        ]);

        if ($data['password'] && ($data['password'] == $data['password_confirm'])) {
            $pocket = Pocket::query()->firstOrCreate([
                'customer_id' => 1,
            ]);

            $pocket->update([
                'password' => Hash::make($data['password']),
            ]);

            return Api::success();
        }

        return Api::failure(410, '两次密码不一致');
    }
}
